package com.baizhi.controller;

import com.baizhi.entrty.Admin;
import com.baizhi.service.AdminService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;

    @RequestMapping("login")
    public String login(Admin admin,HttpSession session){

        //1.封装页面收到的参数
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            session.setAttribute("user",token);
            return "redirect:/main/main.jsp";
        } catch (IncorrectCredentialsException e) {
            return "redirect:/login.jsp";
        } catch (UnknownAccountException s) {
            return "redirect:/login.jsp";
        }
    }

    @RequestMapping("dc")
    public String dc(HttpSession session){
        session.invalidate();
        return "login";
    }

    //注册方法
    @RequestMapping("zc")
    public String zc(String username,String password){
        //先获取uuid
        String uuid = UUID.randomUUID().toString();
        //获取 uuid的前4位
        String substring = uuid.substring(0, 4);
        //加密处理
        Md5Hash md5Hash = new Md5Hash(password, substring, 1024);
        //把加密狗的md5转成 字符串
        String s = md5Hash+"";

        adminService.zc(username,s,substring);

        return "redirect:/login.jsp";
    }



}
